package com.yuanyi.controller;

import com.yuanyi.WebSocketServer;
import com.yuanyi.dao.BaoXiuDanDao;
import com.yuanyi.dao.BaoXiuManDao;
import com.yuanyi.dao.RepairManDao;
import com.yuanyi.entity.BaoXiuDan;
import com.yuanyi.entity.RepairMan;
import com.yuanyi.util.NetUtil;
import com.yuanyi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;

@RestController
public class BaoXiuDanController {
    @Autowired
    BaoXiuDanDao baoXiuDanDao;

    @Autowired
    RepairManDao repairManDao;

    @Resource
    RedisTemplate<String,Object> redisTemplate;

    @Autowired
    BaoXiuManDao baoXiuManDao;

    @GetMapping("/find_bxd")
    public BaoXiuDan find_baoxiandan(int id){
        return baoXiuDanDao.findById(id).get();
    }

    @GetMapping("/jiedan")
    public boolean jiedan(int status,int bxdid) throws IOException {
        BaoXiuDan bxd = baoXiuDanDao.findById(bxdid).get();
        bxd.setStatus(status);
        baoXiuDanDao.save(bxd);
        WebSocketServer.sendInfo(
                "维修完成，请您验收！",
                bxd.getBaoXiuMan().getOpenid());
        return true;
    }

    @PostMapping("/add_baoxiu")
    public BaoXiuDan add_baoxiu(@RequestBody BaoXiuDan baoXiuDan){

        baoXiuManDao.save(baoXiuDan.getBaoXiuMan());

        BaoXiuDan bxd = baoXiuDanDao.save(baoXiuDan);
        String at = (String) redisTemplate.opsForValue().get("access_token");
        //消息队列

        if(bxd!=null){
            Iterable<RepairMan> repairMans = repairManDao.findAll();
            for(RepairMan m:repairMans){
                NetUtil.sendWechatMsg(at,m.getOpenid(),
                        StringUtil.getWechatURL("http://java59.hfbdqn.cn/qiangdan.html?id="+bxd.getId()));
            }
        }
        return bxd;
    }
}
